import React, {useState, useEffect, useRef} from 'react';
import {
  Camera,
  useCameraDevice,
  useCodeScanner,
} from 'react-native-vision-camera';

import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Vibration,
  Dimensions,
  Animated,
} from 'react-native';

import {primaryColor2} from '../theme/default';
import LinearGradient from 'react-native-linear-gradient';
import {BackButton} from './UI/BackButton';

import FlashOnIcon from '../assets/icons/flash-on.svg';
import FlashOffIcon from '../assets/icons/flash-off.svg';
import {useTranslation} from 'react-i18next';

const {height, width} = Dimensions.get('window');

type QRScannerProp = {
  onScanResult: (value: string | undefined | null) => void;
};

export default function QRScanner({onScanResult}: Readonly<QRScannerProp>) {
  const [hasPermission, setHasPermission] = useState(false);
  const [refresh, setRefresh] = useState(false);
  const [scannerLinePosition] = useState(new Animated.Value(128));
  const [torch, setTorch] = useState<'off' | 'on'>('off');
  const device = useCameraDevice('back');
  const {t} = useTranslation();

  const cameraRef = useRef<Camera>(null);

  const toggleFlashlight = async () => {
    setTorch(torch == 'off' ? 'on' : 'off');
  };

  const codeScanner = useCodeScanner({
    codeTypes: ['qr'],
    onCodeScanned: codes => {
      console.log(`onCodeScanned value`, codes[0].value);
      Vibration.vibrate(10);
      onScanResult(codes[0].value);
    },
  });

  useEffect(() => {
    const startScannerAnimation = () => {
      Animated.loop(
        Animated.timing(scannerLinePosition, {
          toValue: new Animated.Value(height - (200 + 80)),
          duration: 2000, // Animation duration for one full cycle (3 seconds)
          useNativeDriver: true,
        }),
      ).start();
    };

    setRefresh(!refresh);
    if (device != null && hasPermission) {
      startScannerAnimation();
    }
  }, [device, hasPermission]);

  useEffect(() => {
    const requestCameraPermission = async () => {
      const permission = await Camera.requestCameraPermission();
      console.log('Camera.requestCameraPermission ', permission);
      setHasPermission(permission === 'granted');
    };

    requestCameraPermission();
  }, []);

  if (device == null || !hasPermission) {
    return (
      <View style={styles.noDeciveOrPermission}>
        <View style={styles.header}>
          <BackButton></BackButton>
        </View>
        <Text style={{color: primaryColor2, fontSize: 14, fontWeight: '600'}}>
          {t('noCameraHint')}
        </Text>
      </View>
    );
  }

  return (
    <View style={styles.mainContainer}>
      <Camera
        torch={torch ?? 'off'}
        ref={cameraRef}
        codeScanner={codeScanner}
        style={StyleSheet.absoluteFill}
        device={device}
        isActive={true}
        enableZoomGesture
      />
      <View style={styles.header}>
        <BackButton></BackButton>
      </View>
      <Animated.View
        style={[
          styles.scannerLine,
          {
            transform: [
              {
                translateY: scannerLinePosition, // Animating the scanner line's Y position
              },
            ],
          },
        ]}>
        <LinearGradient
          colors={['rgba(0, 255, 0, 0)', 'rgba(0, 255, 0, 0.5)']}
          style={styles.gradient}></LinearGradient>
      </Animated.View>
      <View style={styles.footer}>
        <TouchableOpacity
          style={{
            width: 48,
            height: 48,
          }}
          onPress={() => {
            toggleFlashlight();
          }}>
          {torch == 'off' ? (
            <FlashOnIcon
              width={32}
              height={32}
              color={'rgba(255, 255, 255, .8)'}></FlashOnIcon>
          ) : (
            <FlashOffIcon
              width={32}
              height={32}
              color={'rgba(255, 255, 255, .8)'}></FlashOffIcon>
          )}
        </TouchableOpacity>
        <Text style={{color: 'rgba(255, 255, 255, .8)', fontSize: 15}}>
          {t('scanHint')}
        </Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  noDeciveOrPermission: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'black',
  },
  mainContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'black',
  },
  gradient: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scannerLine: {
    position: 'absolute',
    top: 0,
    width: width - 56,
    height: 80, // Height of the scanner line
    backgroundColor: 'transparent',
  },
  header: {
    position: 'absolute',
    top: 64,
    left: 0,
    right: 0,
    paddingLeft: 24,
    height: 50,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  footer: {
    position: 'absolute',
    bottom: 0,
    height: 185,
    left: 0,
    right: 0,
    // backgroundColor: 'red',
    justifyContent: 'center',
    alignItems: 'center',
  },
});
